<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="角色ID">
              <a-input placeholder="请输入" v-model="table.role" />
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item label="状态">
              <a-select placeholder="请选择" v-model="table.value" default-value="2">
                <a-select-option value="2">全部</a-select-option>
                <a-select-option value="0">启用</a-select-option>
                <a-select-option value="1">禁用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="reTable">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="insertRole">新增</a-button>
      <a-popconfirm title="是否删除这些角色?" ok-text="是" cancel-text="否" @confirm="confirm" @cancel="cancel">
        <a-button type="primary" icon="delete">批量删除</a-button>
      </a-popconfirm>

      <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="plsc"><a-icon type="delete" />删除</a-menu-item>
           <a-menu-item key="2"><a-icon type="lock" />锁定</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /> </a-button>
      </a-dropdown> -->
    </div>
    <a-table
      :loading="loading"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :expandedRowKeys="expandedRowKeys"
      rowKey="id"
      ref="table"
      size="default"
      :columns="columns"
      :data-source="loadData"
      @expand="handleExpand"
    >
      <div slot="expandedRowRender" slot-scope="record" style="margin: 0">
        <a-row :gutter="24" :style="{ marginBottom: '12px' }">
          <!-- {{ record }} -->
          <!-- <a-col :span="12" v-for="(role, index) in record.permissions" :key="index" :style="{ marginBottom: '12px' }">
            <a-col :span="4">
              <span>{{ role.permissionName }}：</span>
            </a-col>
            <a-col :span="20" v-if="role.actionEntitySet.length > 0">
              <a-tag color="cyan" v-for="(action, k) in role.actionEntitySet" :key="k">{{ action.describe }}</a-tag>
            </a-col>
            <a-col :span="20" v-else>-</a-col>
          </a-col>-->

          <a-col :span="20" v-if="record.permissions.length > 0">
            <a-tag color="cyan" v-for="(action, k) in record.permissions" :key="k">{{ action.name }}</a-tag>
          </a-col>

          <!-- <a-tree
            checkable
            :tree-data="treeData"
            :default-expanded-keys="['0-0-0', '0-0-1']"
            :default-selected-keys="['0-0-0', '0-0-1']"
            :default-checked-keys="['0-0-0', '0-0-1']"
            :replace-fields="replaceFields"
            @select="onSelect"
            @check="onCheck"
          /> -->
        </a-row>
      </div>
      <span slot="status" slot-scope="status">
        <a-tag color="blue">{{ status | statusFilter }}</a-tag>
      </span>

      <span slot="createTime" slot-scope="createTime">
        <span>{{ createTime | moment }}</span>
      </span>
      <span slot="action2" slot-scope="text, record">
        <a @click="$refs.modal.edit(record)">编辑</a>
        <a-divider type="vertical" />
        <!-- <a-dropdown>
          <a class="ant-dropdown-link"> 更多 <a-icon type="down" /> </a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a href="javascript:;" @click="$refs.modal.watch(record)">详情</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;" @click="$refs.modal.edit(record)">禁用</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;" @click="$refs.modal.del(record)">删除</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown> -->
      </span>
    </a-table>

    <role-modal ref="modal" @ok="handleOk"></role-modal>
  </a-card>
</template>

<script>
import { STable } from '@/components'
import RoleModal from './modules/RoleModal'

const STATUS = {
  0: '启用',
  1: '禁用'
}
const treeData = [
  {
    name: 'parent 1',
    key: '0-0',
    child: [
      {
        name: '张晨成',
        key: '0-0-0',
        disabled: true,
        child: [
          { name: 'leaf', key: '0-0-0-0', disableCheckbox: true },
          { name: 'leaf', key: '0-0-0-1' }
        ]
      },
      {
        name: 'parent 1-1',
        key: '0-0-1',
        child: [{ key: '0-0-1-0', name: 'zcvc' }]
      }
    ]
  }
]
export default {
  name: 'TableList',
  components: {
    STable,
    RoleModal
  },
  data() {
    return {
      loading: false,
      treeData,
      replaceFields: {
        children: 'child',
        title: 'name'
      },
      description:
        '列表使用场景：后台管理中的权限管理以及角色管理，可用于基于 RBAC 设计的角色权限控制，颗粒度细到每一个操作类型。',

      visible: false,
      table: {
        role: '',
        value: '2'
      },

      form: null,
      mdl: {},
      expandedRowKeys: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '唯一识别码',
          dataIndex: 'id',
          align: 'center'
        },
        {
          title: '角色名称',
          dataIndex: 'name',
          align: 'center'
        },
        {
          title: '角色简介',
          dataIndex: 'describe',
          align: 'center'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
          align: 'center'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTime' },

          defaultSortOrder: 'descend',
          sorter: (a, b) => a.createTime - b.createTime,
          align: 'center'
        },
        {
          title: '操作',
          width: '150px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action2' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  created() {
    this.getTable()
  },
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
    moment(value) {
      return new Date(value).toLocaleString() // 你可以根据需要修改格式
    }
  },
  methods: {
    confirm(e) {
      console.log(111, e)
      console.log(222, this.selectedRowKeys)

      this.$message.success('Click on Yes')
    },
    cancel(e) {
      console.log(e)
      this.$message.error('Click on No')
    },
    onSelect(selectedKeys, info) {
      console.log('selected', selectedKeys, info)
    },
    onCheck(checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
    },
    insertRole() {
      this.$refs.modal.add()
    },
    search() {
      // console.log(this.table)
      if (this.table.value !== '2') {
        const roleList = this.removeSpacesFromObject(this.table)
        console.log(roleList)
        this.loading = true
        this.$http.get('/sysRole/search', { params: roleList }).then((res) => {
          if (res.code === 200) {
            this.loadData = []
            this.loading = false
            this.loadData = res.result
            this.expandedRowKeys = res.result.map((item) => item.id)
          }
        })
      } else {
        this.getTable()
      }
    },
    reTable() {
      console.log(this.table)
      this.table = {
        role: '',
        value: '2'
      }
    },
    removeSpacesFromObject(obj) {
      // 去除对象中的每一项数据的空格
      // console.log('obj', obj)

      const newObj = {}
      Object.keys(obj).forEach((key) => {
        newObj[key] = obj[key].replace(/\s+/g, '') // 去除所有空格
      })
      return newObj
    },
    handleExpand(expanded, record) {
      // console.log('expanded', expanded, record)
      if (expanded) {
        this.expandedRowKeys.push(record.id)
      } else {
        this.expandedRowKeys = this.expandedRowKeys.filter((item) => record.id !== item)
      }
    },
    plsc() {
      console.log('批量删除')
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    getTable() {
      this.loading = true
      this.$http.get('/sysRole/getTable').then((res) => {
        if (res.code === 200) {
          this.loading = false
          this.loadData = res.result
          this.expandedRowKeys = res.result.map((item) => item.id)
        }
      })
    },
    handleEdit(record) {
      this.mdl = Object.assign({}, record)

      this.mdl.permissions.forEach((permission) => {
        permission.actionsOptions = permission.actionEntitySet.map((action) => {
          return { label: action.describe, value: action.action, defaultCheck: action.defaultCheck }
        })
      })

      console.log(this.mdl)
      this.visible = true
    },
    handleOk() {
      this.getTable()
      // 新增/修改 成功时，重载列表
      // this.$refs.table.refresh()
    },
    onChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
